import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:stock_check/common/model/checkITDeviceItemDetail.dart';
import 'package:stock_check/common/model/checkInstitutionDetail.dart';
import 'package:stock_check/common/redux/reduxStore.dart';
import 'package:stock_check/common/utils/CommonUtils.dart';
import 'package:stock_check/common/utils/ScanUtils.dart';
import 'package:stock_check/widget/MyScaffold.dart';
import 'package:stock_check/widget/needCheckItemWidget.dart';


class QRViewScan extends StatefulWidget {
  final dynamic item;
  final String type;

  const QRViewScan({Key key, this.item, this.type}) : super(key: key);

  @override
  State<QRViewScan> createState() => _QRViewExampleState();
}

class _QRViewExampleState extends State<QRViewScan> with SingleTickerProviderStateMixin {
  GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  var qrText = "";
  Animation<double> animation;
  AnimationController controller;
  CheckITDeviceItemDetail itDetail;
  CheckInstitutionDetail institutionDetail;
  dynamic item;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.type == 'IT类'){
      itDetail = widget.item;
    }else{
      institutionDetail = widget.item;
    }
    controller = new AnimationController(duration: const Duration(seconds: 3), vsync: this);
    animation=CurvedAnimation(parent: controller, curve: Curves.ease);
    animation = new Tween<double>(begin: 0.0, end: 200.0).animate(controller)
    ..addListener((){
      setState(() {

      });
    });

    animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        controller.reverse();
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();
      }

    });
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    var child = Stack(
      fit: StackFit.expand,
      alignment: Alignment.bottomCenter,
      children: <Widget>[
        Container(
          width: double.infinity,
          height: CommonUtils.getScreenHeight(context)/1.5,
          child: QRView(
            key: qrKey,
            onQRViewCreated: _onQRViewCreated,
          ) ,
        ),
        Positioned(
          top: CommonUtils.getScreenHeight(context)/4,
          width: 200.0,
          height: 200.0,
          child:CustomPaint(
            size: Size(200, 200), //指定画布大小
            painter: MyPainter(),
            foregroundPainter: LinePainter(animation.value),
          ),
        ),
        Positioned(
            width: CommonUtils.getScreenWidth(context)-20,
            height: 150.0,
            bottom: 30.0,
            child: _renderItem()
        )
      ],
    );
    return StoreBuilder<StockState>(builder: (context, store) {
      return MyScaffold(
        title: Text('二维码扫描'),
        noLeading: true,
        store: store,
        child: child,
      );
    });
  }

  @override
  void dispose() {
    qrKey = null;
    controller.dispose();
    // TODO: implement dispose
    super.dispose();
  }

  @override
  void didUpdateWidget(QRViewScan oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
  }

  void _onQRViewCreated(QRViewController controller) {
    final channel = controller.channel;
    controller.init(qrKey);
    channel.setMethodCallHandler((MethodCall call) async {
      switch (call.method) {
        case "onRecognizeQR":
          dynamic arguments = call.arguments;
          // 和上次一样的就忽略
          if(qrText==arguments.toString()) return;
          setState(() {
            qrText = arguments.toString();
            bool flag = false;
            if(widget.type=='IT类'){
              for(int i=0;i<itDetail.assetsList.length;i++){
                if(itDetail.assetsList[i].eqptNo == qrText){
                  setState(() {
                    flag = true;
                    item = itDetail.assetsList[i];
                    if(itDetail.curStartTimeStr.isEmpty)
                      itDetail.curStartTimeStr = CommonUtils.getCurrentTime();
                  });
                  break;
                }
              }
              if(!flag){
                Fluttertoast.showToast(msg: '暂未找到该资产！',toastLength: Toast.LENGTH_LONG);
              }
            }else{
              for(int i=0;i<institutionDetail.assetsList.length;i++){
                if(institutionDetail.assetsList[i].eqptNo == qrText){
                  setState(() {
                    flag = true;
                    item = institutionDetail.assetsList[i];
                    if(institutionDetail.curStartTimeStr.isEmpty) institutionDetail.curStartTimeStr = DateTime.now().toString();
                  });
                  break;
                }
              }
              if(!flag){
                Fluttertoast.showToast(msg: '暂未找到该资产！',toastLength: Toast.LENGTH_LONG);
              }
            }
          });
      }
    });
  }

  _renderItem() {
    return item != null?
        Column(
          children: <Widget>[
            NeedCheckItemWidget(
                item: item,
                type: widget.type,
                detail: widget.type=='IT类'?itDetail:institutionDetail,
                context: context)
          ],
        ):
    Container(
      child: Center(
        child: Text('请扫描二维码...',style: TextStyle(
          color: Colors.white,
          fontWeight: FontWeight.bold
        ),),
      ),
    );
  }
}



//    Path path = Path()..moveTo(5, currentPosition);
//    for(int i=1;i<=size.width;i++){
//      if(i*10>size.width)break;
//      if(i%2==1){
//        path.lineTo(i*10.0+5, currentPosition);
//      }else{
//        path.moveTo(i*10.0+5, currentPosition);
//      }
//    }
